package com.mtt.thirdapi.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class ParseMD5 {
    /**
     * 32位小写MD5
     *
     * @param str
     * @return
     */
    public static String parseStrToMd5L32(String str) {

        if (null == str) {
            log.warn(".parseStrToMd5L32() str is null.");
            return str;
        }

        String reStr = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(str.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                int bt = b & 0xff;
                if (bt < 16) {
                    sb.append(0);
                }
                sb.append(Integer.toHexString(bt));
            }

            reStr = sb.toString();

            return reStr;

        } catch (Exception e) {
            log.error(".parseStrToMd5L32() Exception={},param={}", e, str,
                    e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 32位大写MD5
     *
     * @param str
     * @return
     */
    public static String parseStrToMd5U32(String str) {
        String reStr = parseStrToMd5L32(str);
        if (null != reStr) {
            reStr = reStr.toUpperCase();
        }
        return reStr;
    }


    /**
     * 加密
     *
     * @param origin      要被加密的字符串
     * @param charsetname 加密字符,如UTF-8
     * @DATE 2018年9月11日 下午2:12:51
     */
    public static String MD5EncodeForHex(String origin, String charsetname)
            throws UnsupportedEncodingException, NoSuchAlgorithmException {
        return MD5EncodeForHex(origin.getBytes(charsetname));
    }

    public static String MD5EncodeForHex(byte[] origin) throws NoSuchAlgorithmException {
        return Hex.encodeHexString(digest("MD5", origin));
    }

    /**
     * 指定加密算法
     *
     * @throws NoSuchAlgorithmException
     * @DATE 2018年9月11日 下午2:11:58
     */
    private static byte[] digest(String algorithm, byte[] source) throws NoSuchAlgorithmException {
        MessageDigest md;
        md = MessageDigest.getInstance(algorithm);
        return md.digest(source);

    }


}
